<template>
  <base-modal
    :title="title"
    :width="selectedTemplate ? '500px' : '466px'"
    @cancel="handleCancel"
    :show.sync="isShow"
    :mask-closeable="false"
  >
    <!--start 新建事件类型 -->
    <template v-if="!selectedTemplate">
      <div class="template-list">
        <el-card
          class="choose-type-box"
          :class="{ active: item.type === hoverTemplateType }"
          :style="{ 'background-image': 'url(' + item.bgImg + ')' }"
          shadow="hover"
          v-for="item in serviceEventTemplateList"
          :key="item.type"
          @click.native="selectedTemplate = item.type"
          @mouseenter.native="hoverTemplateType = item.type"
          @mouseleave.native="hoverTemplateType = ''"
        >
          <div class="choose-type-box-content">
            <h2>{{ item.title }}</h2>
            <p class="task-type-desc">{{ item.desc }}</p>
          </div>
        </el-card>
      </div>
    </template>
    <!--end 新建事件类型 -->

    <!--start 选择模板 -->
    <template v-else>
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        
        label-position="top"
        class="form-wrap"
      >
        <el-form-item
          v-if="selectedTemplate === 'exist'"
          :label="$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.label1')"
          prop="templetId"
        >
          <el-select v-model="form.templetId" :placeholder="$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.label1')">
            <el-option
              v-for="item in serviceEventTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-for="(v,i) in fields" :key="i" :label="v.label" :prop="`nameLanguage.${[v.language]}`">
          <el-input
            v-model="form.nameLanguage[v.language]"
            :placeholder="$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.pla1', {count: NAME_MAX})"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <ul class="statecolor">
            <li
              v-for="color in typeColors"
              :key="color"
              @click="form.color = color"
              :style="{ background: color }"
            >
              <i class="el-icon-check" v-if="color === form.color"></i>
            </li>
          </ul>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="handleCancel">{{$t('common.base.cancel')}}</el-button>
        <el-button
          :loading="pending"
          type="primary"
          @click="createEventType"
        >{{$t('common.base.confirm')}}</el-button
        >
      </div>
    </template>
    <!--end 选择模板 -->
  </base-modal>
</template>

<script>
import { getOssUrl } from '@src/util/assets' 
/** assets */
const taskTemplateBlank = getOssUrl('/setting/task-template-blank.png');
const taskTemplateCopy = getOssUrl('/setting/task-template-copy.png');
/** api */
import { addEventType } from '@src/api/SettingServiceEventApi';
/** until */
import { TYPE_COLORS } from '../../../constant.js';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
import i18n from '@src/locales'

let { isOpenMultiLanguage, languagesList } = useFormMultiLanguage()

const NAME_MAX = 100;

const validateTypeName = (rule, value, callback) => {
  // if (value === '') return callback(new Error('请输入事件类型名称'));
  if (value.length > NAME_MAX) callback(new Error(i18n.t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.tips1', {count: NAME_MAX})));
  // if(!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) return callback(new Error('请输入中文、字母、数字'));

  callback();
};
export default {
  name:'add-service-event-dialog',
  props: {
    visiable: {
      type: Boolean,
      default: false,
    },
    serviceEventTypeList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      isShow: false, //  模态框是否展示
      pending: false, //  确定按钮 loading
      hoverTemplateType: '', //  选择模板 hover
      selectedTemplate: '', //  选择模板
      form: {
        templetId: '',
        typeName: '',
        color: '',
        nameLanguage:{}
      },
      rules: {
        templetId: [
          { required: true, message: i18n.t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.tips2'), trigger: 'blur' },
        ],
        typeName: [
          { required: true, message: i18n.t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.tips3'), trigger: 'blur' },
          { validator: validateTypeName, trigger: 'blur' },
        ],
      },
      fields:[],
      NAME_MAX
    };
  },
  computed: {
    title() {
      return (
        (this.serviceEventTemplateList.find(
          template => template.type === this.selectedTemplate
        ) || {}).title ||  this.$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.title1')
      );
    },
    serviceEventTemplateList() {
      return [
        {
          type: 'blank',
          title: this.$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.title2'),
          desc: this.$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.des1'),
          bgImg: taskTemplateBlank,
        },
        {
          type: 'exist',
          title: this.$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.title3'),
          desc: this.$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.des2'),
          bgImg: taskTemplateCopy,
        },
      ];
    },
    typeColors() {
      return TYPE_COLORS;
    },
  },
  watch: {
    visiable(newValue) {
      this.isShow = newValue;
    },
  },
  mounted() {
    this.resetForm();
  },
  methods: {
    /** 创建服务事件类型 */
    async createEventType() {
      try {
        const validateRes = await this.$refs.form.validate();
        if (!validateRes) return;

        this.pending = true;
        try {
          // typeName默认读取zh语言的值
          this.form.typeName = this.form.nameLanguage['zh']
          const {status, data, message} = await addEventType(this.form);
          if (status == 0) {
            //  流程设置页面跳转
            this.handleRouterGoFlowEdit(data);
          } else {
            this.$message.warning(message);
          }
        } catch (e) {
          console.error(e);
        } finally {
          this.pending = false;
        }

      } catch (error) {
        console.warn(`[表单检测不通过] ${JSON.stringify(this.form)}`);
      }
    },
    handleCancel() {
      this.$emit('update:visiable', false);
      setTimeout(() => {
        this.resetSelectTemplate();
        this.resetForm();
      }, 100);
    },
    /** 初始化/重置 form*/
    resetForm() {
      this.form = {
        templetId: '',
        typeName: '',
        color: this.typeColors[0],
        nameLanguage:{}
      };
      this.initFields()
    },
    /** 重置选择模板*/
    resetSelectTemplate() {
      this.selectedTemplate = '';
    },
    /** 跳转流程设置*/
    handleRouterGoFlowEdit(id) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'service_event_flow_setting',
      //   title: '服务事件类型设置',
      //   url: `/setting/serviceStation/eventForm?serviceEventTypeId=${id}&new=true`,
      //   reload: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventFlowSetting,
        params: `serviceEventTypeId=${id}&new=true`,
        // titleKey: '服务事件类型设置',
        reload: true,
        fromId,
      })
      // 刷新列表页
      this.$platform.refreshTab(fromId); 
    },
    initFields(){

      let fields = [
        {
          language: 'zh',
          label: isOpenMultiLanguage ? this.$t('common.base.language.ChineseName') : this.$t('common.base.name'),
        },
        {
          language: 'en',
          label:this.$t('common.base.language.EnglishName'),

        },
        {
          language: 'ja',
          label:this.$t('common.base.language.JapaneseName'),
        },
        {
          language: 'ko',
          label:this.$t('common.base.language.KoreaName'),
        }
      ]

      // 这里在useFormMultiLanguage里处理了只剩一个了
      // if(!isOpenMultiLanguage){
      //   languagesList = [languagesList[0]]
      // }

      let languagesKeys = languagesList.map(v=>v.language)

      languagesKeys.map(key=>{
        this.$set(this.form.nameLanguage, key, '')
        this.rules[`nameLanguage.${key}`] = [
          { required: false, message: this.$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.tips3'), trigger: 'blur' },
          { validator: validateTypeName, trigger: 'blur' },
        ]
      })
      // 中文必填
      this.rules['nameLanguage.zh'] = [
        { required: true, message: this.$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.tips3'), trigger: 'blur' },
        { validator: validateTypeName, trigger: 'blur' },
      ]
      this.fields = fields.filter((v)=>languagesKeys.includes(v.language))
    }
  },
};
</script>

<style lang="scss" scoped>
.template-list {
  display: flex;
  justify-content: space-between;
  max-height: 324px;
  padding: 40px;
  overflow: hidden;
  .choose-type-box {
    cursor: pointer;
    position: relative;
    width: 183px;
    height: 244px;
    border-radius: 10px;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;

    &.active {
      .choose-type-box-content {
        transform: translateY(0);
        p {
          opacity: 1;
        }
      }
    }

    .choose-type-box-content {
      position: absolute;
      left: 16px;
      bottom: 17px;
      color: #ffffff;
      transform: translateY(22px);
      transition: all 0.5s ease;

      h2 {
        margin-bottom: 5px;
        font-size: 16px;
      }
      p {
        margin-bottom: 0;
        font-size: 12px;
        opacity: 0;
        transition: all 0.5s ease;
      }
    }
  }
}

.form-wrap {
  padding: 20px;
  ul.statecolor {
    width: 280px;
    padding: 0;
    line-height: 22px;
    li {
      list-style: none;
      display: inline-block;
      cursor: pointer;
      margin-right: 4px;
      width: 32px;
      height: 22px;
      vertical-align: middle;
      i {
        position: relative;
        font-weight: bold;
        left: 9px;
        color: #fff;
      }
    }
  }
}

.el-select {
  width: 100%;
}
::v-deep .el-input{
  width: 280px;
}
</style>
